// pages/publish/detail/publish/publish.js
import { request } from '../../../../request/index.js'
Page({
  data: {
    title: '',
    text: '',
    variety: '',
    fileList: [],
    editorContent: '', // 用于保存编辑器的内容
  },

  //删除图片
  deleteImg() {
    this.setData({
      fileList: []
    });
  },

  // 在选择文件后触发

  afterRead(event) {
    const token = wx.getStorageSync('token');
    const {
      file
    } = event.detail;
    let that = this
    //回显图片,设置为正在上传
    that.setData({
      fileList: [{
        url: file.url,
        name: '文章封面',
        status: 'uploading',
        message: '上传中',
      }]
    })
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
      url: 'http://localhost:8080/upload',
      filePath: file.url, //传递的url
      name: 'file', //后端参数名
      header: {
        "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
        "author": token ? token : '',
      },
      formData: {},
      success: function (res) {
        let data = res.data;
        //wx.uploadFile默认返回的数据为字符串
        //将字符串解析为json格式数据
        try {
          data = JSON.parse(data);
          console.log(data.data);
          that.setData({
            fileList: [{
              url: data.data,
              name: '文章封面',
            }]
          })
        } catch (error) {
        }
      },
    })
  },
  onEditorReady() {
    const that = this;
    const query = wx.createSelectorQuery();
    query.select('#editor').context().select('#editor').context()
    query.exec(function (res) {
      that.editorCtx = res.context;
    });
  },
  // 设置编辑器内容
  setContents(html) {
    this.editorCtx.setContents({
      html: html,
      success: function (res) {
        // 设置成功
      }
    });
  },
  // 获取编辑器内容
  getContents() {
    this.editorCtx.getContents({
      success: function (res) {
        console.log(res.text) // 获取到的文本内容
      }
    });
  },
  saveScience() {
    const token = wx.getStorageSync('token');
    const that = this;
    let data = {
      title: that.data.title,
      petVariety: that.data.variety,
      text: that.data.text,
      pic: that.data.fileList[0].pic ? that.data.fileList[0].pic : '',
    }
    console.log(data);
    request({
      url: '/petScience/add',
      method: 'PUT',
      data: data,
      header: {
        'author': token ? token : '',
      }
    }).then(res => {
      if (res.code === 0){
        wx.showToast({
          title: '成功',
          icon: 'success'
        })
      } else {
        wx.showToast({
          title: '错误',
          icon: 'error'
        })
      }
    })
  }
})